package hendler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"new/cache"
	"new/model"
	"new/pkj"
	"strconv"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}
	redis_key := "error_login_" + username
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if cacheData == 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误三次，禁止登录",
		})
		return
	}
	var user model.User
	err := model.DB.Where("username = ?", username).Find(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户不存在",
		})
		return
	}
	if user.Password != pkj.Str(password) {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if cacheData == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Second*180)
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "密码错误三次，封禁3分钟",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
	})
	return
}
func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	var novels []model.Novel
	offset := (page - 1) * size

	var total int64
	model.DB.Model(&model.Novel{}).Count(&total)
	redis_key := "list_" + strconv.Itoa(page)

	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Offset(offset).Limit(size).Debug().Find(&novels)
		jsonData, _ := json.Marshal(&novels)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Second*180)
	} else {
		json.Unmarshal([]byte(cacheData), &novels)
	}
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "ok",
		"data":  novels,
		"total": total,
	})
}
func ListGETID(c *gin.Context) {
	id := c.Query("id")
	var novel model.Novel

	reids_key := "list_GET_" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, reids_key).Result()
	if cacheData == "" {
		model.DB.Where("id=?", id).Find(&novel)
		jsonData, _ := json.Marshal(&novel)
		cache.Rdb.Set(cache.Ctx, reids_key, jsonData, time.Second*180)
	} else {
		json.Unmarshal([]byte(cacheData), &novel)
	}
	var total int64
	model.DB.Model(&model.Novel{}).Debug().Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "ok",
		"data":  novel,
		"total": total,
	})

}
